package com.fuyao.cloud.common.core.annotation;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class ValidationDateTimeValid implements ConstraintValidator<ValidationDateTime, String> {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN, Locale.CHINA);
    private String msg = null;

    @Override
    public void initialize(ValidationDateTime constraintAnnotation) {
        this.msg = String.format("时间格式错误：%s", msg);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isEmpty(value)) {
            return true;
        }
        String date = value.replaceAll("/", "-");
        final DateTimeFormatter dateFormatter = DATE_FORMATTER.withResolverStyle(ResolverStyle.STRICT);
        final DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter);
        return validator.isValid(date);
    }

}
